package com.future.taskdemo.config;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Metrics;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author wanghuainan
 * @date 2020/9/8
 */
@RestController
@RequestMapping("/promethues/")
@Slf4j
public class PrometheusController {

    @Autowired
    MeterRegistry registry;

    /**
     * 指标类型设置
     */
    private Counter counter_core;
    private Counter counter_index;
    private AtomicInteger app_online_count;

    /**
     * 服务启动时创建自定义指标
     */
    @PostConstruct
    private void init() {
        counter_core = registry.counter("app_requests_method_count", "method", "PrometheusController.core");
        counter_index = registry.counter("app_requests_method_count", "method", "PrometheusController.index");
        app_online_count = registry.gauge("app_online_count", new AtomicInteger(0));
    }


    /**
     * 监控平台是否可用，没调用一次就记录一次，每次调用就加一
     *
     * @return
     */
    @GetMapping("testIsUsable")
    public String testIsUsable() {
        Metrics.counter("监控测试", "two", "李四", "one", "张三", "three", "王二").increment();
        counter_index.increment();
        return counter_index.count() + " index of springboot-prometheus.";
    }

    /**
     * 监控平台核心接口请求次数
     *
     * @return
     */
    @GetMapping("testIsCore")
    public String testIsCore() {
        counter_core.increment();
        return counter_core.count() + " index of springboot-prometheus.";
    }

    /**
     * 测试实时在线人数，动态数据，每次请求数据可能都不一样
     *
     * @return
     */
    @RequestMapping(value = "/online")
    public Object online() {
        int people = 0;
        try {
            people = new Random().nextInt(2000);
            app_online_count.set(people);
        } catch (Exception e) {
            return e;
        }
        //return R.error(HuobiResultCode.PARAM_ERROR);
        return "current online people: " + people;
    }

}